<template>
	<div :class="$style['tree-container']">
		<div :class="$style['tree-tools-wrapper']">
			<el-link :underline="false" type="primary" :icon="Plus" @click="openAddDialog(1)" />
			<el-link :underline="false" type="primary" :disabled="!info.id" :icon="Edit" @click="openAddDialog(2)" />
			<el-link :underline="false" type="danger" :disabled="!info.id" :icon="Delete" @click="removeItem" />
		</div>
		<el-tree :class="$style['tree-wrapper']" :data="groups" ref="treeRef" node-key="id" highlight-current
			:props="defaultProps" @node-click="handleNodeClick" :expand-on-click-node="false">
			<template #default="{ data }">
				<div :class="$style['node-item']">
					<el-icon>
						<Folder />
					</el-icon>
					<span>{{ data.name }}</span>
				</div>
			</template>
		</el-tree>
	</div>
	<el-dialog v-model="addFormShow" :title="addForm.id ? '编辑人员组织' : '新增人员组织'" width="500" :close-on-click-modal="false"
		:close-on-press-escape="false">
		<el-form :model="addForm" label-width="auto" ref="addFormRef" :rules="rules">
			<el-form-item label="组织名称" prop="name">
				<el-input v-model="addForm.name" placeholder="请输入组织名称" clearable />
			</el-form-item>
			<el-form-item label="上级组织">
				<el-cascader :options="trees" ref="groupCascaderRef" v-model="addForm.pid" :props="props"
					placeholder="请选择上级组织" style="width:100%;" clearable />
			</el-form-item>
		</el-form>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="addFormShow = false">取消</el-button>
				<el-button type="primary" @click="onSubmit">确认</el-button>
			</div>
		</template>
	</el-dialog>
</template>

<script setup>
import { ref, onMounted, nextTick, reactive } from 'vue'
import { Plus, Edit, Delete, Folder } from '@element-plus/icons-vue'
import { fetchUserGroup, fetchCreateGroup, fetchRemoveGroup } from '@/api/user.services'
import { ElMessage, ElMessageBox } from 'element-plus'
const emits = defineEmits(['nodeClick', 'delete'])
const groups = ref([])
const defaultProps = ref({
	id: "id",
	children: "children",
	label: "name"
})
const addFormRef = ref(null)
const addForm = ref({})
const info = ref({})
const treeRef = ref(null)
const handleNodeClick = (data) => {
	info.value = {}
	if (data.id) {
		info.value = data
	}
	emits('nodeClick', data)
}
const initGroups = async () => {
	const result = await fetchUserGroup()
	if (result.code == 1) {
		groups.value = result.data
		const id = info.value?.id || 0
		nextTick(() => {
			treeRef.value.setCurrentKey(id)
		})
	}
}
onMounted(() => {
	initGroups()
})
const addFormShow = ref(false)
const props = {
	label: "name",
	value: "id",
	children: "children",
	checkStrictly: true,
	emitPath: false
}
const trees = ref([])
const openAddDialog = (type) => {
	trees.value = []
	if (type == 1) {
		addForm.value = {}
		trees.value = groups.value[0].children
	} else {
		addForm.value = JSON.parse(JSON.stringify(info.value))
		addForm.value.pid = addForm.value.pid || null
		const children = groups.value[0].children
		// 递归过滤掉当前节点及其子节点
		const filterChildren = (items) => {
			return items.filter(item => {
				// 排除当前节点
				if (item.id === info.value.id) return false

				// 如果有子节点，递归过滤
				if (item.children && item.children.length) {
					item.children = filterChildren(item.children)
				}
				return true
			})
		}
		trees.value = filterChildren(JSON.parse(JSON.stringify(children)))
	}
	addFormShow.value = true
}
const rules = reactive({
	name: [{ required: true, message: '请输入组织名称', trigger: 'blur' }]
})
const removeItem = async () => {
	if (!info.value.id) {
		ElMessage.warning('请选择要删除的组织')
		return
	}
	try {
		await ElMessageBox.confirm('确定要删除选择的组织吗？', '提示', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning'
		})
		const result = await fetchRemoveGroup({ id: info.value.id })
		if (result.code == 1) {
			emits('delete')
			initGroups()
			info.value = {}
			addForm.value = {}
			ElMessage.success('删除成功')
		}
	} catch (error) {
		console.error(error)
	}
}
const onSubmit = async () => {
	try {
		const valid = await addFormRef.value.validate()
		if (!valid) return
		const result = await fetchCreateGroup(addForm.value)
		if (result.code == 1) {
			initGroups()
			if (addForm.value?.id) {
				info.value = addForm.value
			}
			ElMessage.success(addForm.value.id ? '修改成功' : '添加成功')
			addForm.value = {}
			addFormShow.value = false
		}
	} catch (error) {
		console.error(error)
	}
}
</script>

<style lang="scss" module>
.tree-container {
	flex: 240px 0 0;
	border-right: 1px solid rgba(50, 58, 78, 0.16);
	padding: 0 5px 5px 5px;
	display: flex;
	flex-direction: column;
}

.tree-tools-wrapper {
	display: flex;
	height: 35px;
	justify-content: space-between;
	align-items: center;
	border-bottom: 1px solid rgba(50, 58, 78, 0.16);
}

.tree-wrapper {
	@include highlight;
}

.node-item {
	& [class~='el-icon'] {
		margin-right: 5px;
	}

}
</style>
